import sys
import os
import glob


class AutoFileExport(object):
    """
        从svn的历史列表中取到对应的源文件，生成增量包
        cyw 2015-04-22
    """

    def __init__(self):
        # 文件列表，每行一条记录
        self.list = []
        # svn历史文件目录
        self.filePath = ""
        # svn项目名
        self.projectName = ""
        # 复制文件的目标目录
        self.sourcePath = ""
        # 复制文件的源目录
        self.targetPath = ""
        # 路径中要去掉的文字
        self.replaceTxt = "/protal/代码/trunk/"

    def inSvnListFile(self):
        '''1.输入svn中更新的文件列表'''
        file = open(self.filePath, 'r')
        line = file.readline()
        while (line):
            if line.find(self.projectName) >= 0:
                temp = self.analyzeTxtLin(line)
                self.list.append(temp)

                # 查找内部类
                end = temp.find('.class')
                top = temp.rfind('/')
                if end > 0:
                    fileName = temp[0:end] + "*"
                    fileName = fileName.replace(self.replaceTxt + 'src/main/java'
                                                ,self.sourcePath + 'WebContent/WEB-INF/classes')
                    tempList = self.traversalFile(fileName)
                    for item in tempList:
                        self.list.append(item)
            line = file.readline()
        file.close()

    def joinPath(self):
        '''拼合路径'''
        # 类文件列表
        classList = []
        for line in self.list:
            if line.find('.jsp') > 0:
                sourceTemp = line.replace(self.replaceTxt, self.sourcePath)
                targetTemp = sourceTemp.replace(self.sourcePath, self.targetPath)
            elif line.find('.jar') > 0:
                sourceTemp = line.replace(self.replaceTxt, self.sourcePath)
                targetTemp = sourceTemp.replace(self.sourcePath, self.targetPath)
            elif line.find('.class') > 0:
                # print(self.replaceTxt+'src\\main\\java','------------',self.sourcePath+'WebContent/WEB-INF/classes')
                sourceTemp = line.replace(self.replaceTxt + 'src/main/java',
                                          self.sourcePath + 'WebContent/WEB-INF/classes')
                targetTemp = sourceTemp.replace(self.sourcePath, self.targetPath)
                #print(sourceTemp, targetTemp)
                targetTemp = sourceTemp.replace(self.sourcePath, self.targetPath)
                classList.append(sourceTemp)
            elif line.find('.js') > 0 or line.find('.gif') > 0 or line.find('.png') > 0 or line.find(
                    '.jpg') > 0 or line.find('.css') > 0:
                sourceTemp = line.replace(self.replaceTxt, self.sourcePath)
                targetTemp = sourceTemp.replace(self.sourcePath, self.targetPath)
            elif line.find('.xml') > 0:
                if line.find('resources') > 0:
                    sourceTemp = line.replace(self.replaceTxt+'src/main/resources',self.sourcePath+'WebContent/WEB-INF/classes')
                    targetTemp = sourceTemp.replace(self.sourcePath,self.targetPath)
                elif line.find('WEB-INF') > 0:
                    sourceTemp = line.replace(self.replaceTxt, self.sourcePath)
                    targetTemp = sourceTemp.replace(self.sourcePath, self.targetPath) 
            elif line.find('.tld') > 0:
                sourceTemp = line.replace(self.replaceTxt, self.sourcePath)
                targetTemp = sourceTemp.replace(self.sourcePath, self.targetPath)
            else:
                sourceTemp = ''
            if sourceTemp != '':
                self.moveFile(sourceTemp, targetTemp)


    def moveFile(self, source, target):
        '''移动文件'''
        targetParent = target[0:target.rfind('/')]
        # print('target',target)
        if source != '' and target != '':
            source = source.replace("\n", "")
            target = target.replace("\n", "")
            # E:\payspace\Protal\WebContent\WEB-INF\views\common\login\login.jsp
            # E:\payspace\Protal\WebContent\index.jsp
            # print("0:",os.path.isfile("E:/payspace/Protal/WebContent/WEB-INF/views/common/login/login.jsp"))
            #print("1:"," :"+source+":")
            if os.path.isfile(source):
                if not os.path.exists(targetParent):
                    os.makedirs(targetParent)
                open(target, 'wb+').write(open(source, 'rb').read())
                print('成功复制：', target)

    def analyzeTxtLin(self, mtxt):
        '''解析svn历史文本'''
        # mtxt = mtxt.replace(self.replaceTxt,'')
        # mtxt = mtxt.replace(self.replaceTxt+"main/webapp/WEB-INF/",'')
        # if mtxt.find(self.projectName)>=0:
        mtxt = mtxt.replace('.java', '.class')
        mtxt = mtxt.replace('Modified : ', '')
        mtxt = mtxt.replace('Added : ', '')
        mtxt = mtxt.replace('\\', '/')
        # line = mtxt.split(" ")
        #tempLine = []
        #print(1,line)
        #for item in line:
        #	if item != "":
        #		tempLine.append(item)
        #	line = tempLine
        #print(2,line)
        #return line
        #print("mtxt:",mtxt)
        return mtxt


    def traversalFile(self, fileName):
        '''
        根据文件名查找文件
        支持模糊查询
        '''
        reList = []
        if fileName is not None:
            for item in glob.glob(fileName):
                reList.append(item)
        return reList


if __name__ == '__main__':
    afe = AutoFileExport()
    afe.filePath = "F:\\work\\python\\log.txt"
    afe.sourcePath = "D:/develop/running/worksapce2/Protal/"
    afe.targetPath = "F:/work/python/target/"
    afe.projectName = "protal"
    afe.inSvnListFile()
    afe.joinPath()
    # 查询内部类
    # afe.traversalFile("E:\payspace\Protal\WebContent\WEB-INF\classes\org\whale\protal\yuntongxun\SmsSend*")
    #E:/payspace/Protal/WebContent/WEB-INF/classes/org/whale/protal/common/ExpireSet*
    #afe.traversalFile("E:/payspace/Protal/WebContent/WEB-INF/classes/org/whale/protal/common/ExpireSet*")
